#!/bin/bash
PACKETSIZE=3223
PORT=2222
TARGET=127.0.0.1
TESTTIME=5
THREADS=6
DRIVES=12
UDPBIN=udpmon_extra-1.2.6/udpmon_send
MAXMEM=5
MINMEM=4
METHODS=(def aio splice)
#VERBOSE=" > /dev/null"
EXTRA_PARAMS=$*
DEFAULT_PARAMS="-I $MINMEM -A $MAXMEM -s $PORT -d $DRIVES"

NRHUGE=`cat /proc/sys/vm/nr_hugepages | head -c -1`
if [ "$NRHUGE" -ne "0" ]
then
  DEFAULT_PARAMS="$DEFAULT_PARAMS -u "
fi

WAIT=40
echo "setting up non-daemon mode"
./configure --enable-daemon=no --enable-logtofile=no &> /dev/null
make &> /dev/null

if [ $? -ne 0 ]
then
  echo "Error in compilation"
  exit -1
fi

NRHUGE=`cat  /proc/sys/vm/nr_hugepages`
if [ $NRHUGE -ne 0 ]
then
  DEFAULT_PARAMS="$DEFAULT_PARAMS -u "
fi

echo "Cleaning up leftovers from previous test"
for i in /mnt/disk*
do
for j in "${METHODS[@]}"
do 
  rm  -rf $i/multi_$j &> /dev/null
  rm  -rf $i/one_$j &> /dev/null
done
done

echo "Testing sending with nonexisting files"
for i in "${METHODS[@]}"
do
  src/vlbistreamer $EXTRA_PARAMS $DEFAULT_PARAMS -m s $THREADS -w $i this_should_not_exist 127.0.0.1 &> /dev/null
  #Identical lines, but the other gives an error WTF?
  #if [ ! $? -eq 0 ]
  if [ $? -eq 0 ]
  then
    echo "Started sending, eventhought no file on $i writer!"
    exit -1
  fi
  echo -e ". $i\t\tok"
done
echo -e "Nonexisting files test ... \tOK"
echo "Testing receiving/sending from localhost on 1 thread"
for i in "${METHODS[@]}"
do
  echo -e "Testing writing $i"
  $UDPBIN -u $PORT -p $PACKETSIZE -t $((TESTTIME*2)) -d $TARGET -w $WAIT > /dev/null &
  src/vlbistreamer $DEFAULT_PARAMS $EXTRA_PARAMS -m r -w $i -p $PACKETSIZE one_$i $TESTTIME  
  if [ ! $? -eq 0 ]
  then
    echo "Error on one thread $i writer"  
    exit -1
  fi
  #Kills the sender. Doesn't actually work :/
  killall udpmon_send
  echo -e "$i writer one thread ... \tOK"
  echo -e "Testing sending $i"
  src/vlbistreamer $DEFAULT_PARAMS -m s $EXTRA_PARAMS -w $i -p $PACKETSIZE one_$i $TARGET 
  if [ ! $? -eq 0 ]
  then
    echo "Error on one thread $i writer"  
    exit -1
  fi
  echo -e "$i sending one thread ... \tOK"
done
for i in "${METHODS[@]}"
do
  echo -e "Testing writing $THREADS threads with $i"
  $UDPBIN -u $PORT -p $PACKETSIZE -t $((TESTTIME*2)) -d $TARGET -w $WAIT > /dev/null &
  src/vlbistreamer $DEFAULT_PARAMS $EXTRA_PARAMS -m r -w $i -p $PACKETSIZE multi_$i $TESTTIME  
  if [ ! $? -eq 0 ]
  then
    echo "Error on $THREADS threads $i writer"  
    exit -1
  fi
  #Kills the sender. Doesn't actually work :/
  killall udpmon_send
  echo -e "$i writer $THREADS threads ... \tOK"
  echo -e "Testing sending $i"
  src/vlbistreamer  $DEFAULT_PARAMS -m s  $EXTRA_PARAMS -w $i -p $PACKETSIZE multi_$i $TARGET  
  if [ ! $? -eq 0 ]
  then
    echo "Error on $THREADS threads $i writer"  
    exit -1
  fi
  echo -e "$i sending $THREADS threads ... \tOK"
done

echo "Cleaning up"
for i in /mnt/disk*
do
for j in "${METHODS[@]}"
do 
  rm -rf $i/multi_$j &> /dev/null
  rm -rf $i/one_$j &> /dev/null
done
done


exit 0
